using System;
using System.Threading.Tasks;
using VOL.Core.Utilities;
using VOL.demo.IRepositories;
using System.Collections.Generic;
using VOL.Entity.DomainModels;
using VOL.demo.IServices;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.SystemModels;
using System.Linq;
using VOL.Core.ManageUser;
using VOL.Core.BaseProvider;

namespace VOL.demo.Services
{
    public partial class SalesReturnOrderModelService
    {
        /// <summary>
        /// 分页查询销售退货订单
        /// </summary>
        public async Task<WebResponseContent> GetSalesReturnOrderPageListAsync(
            int pageIndex, 
            int pageSize, 
            string orderCode = null, 
            int? status = null, 
            long? supplierId = null, 
            DateTime? returnDate = null)
        {
            try
            {
                var result = await repository.GetSalesReturnOrderPageListAsync(
                    pageIndex, pageSize, orderCode, status, supplierId, returnDate);

                return new WebResponseContent
                {
                    Status = true,
                    Message = "查询成功",
                    Data = new
                    {
                        Data = result.Data,
                        TotalCount = result.TotalCount,
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        TotalPages = (int)Math.Ceiling((double)result.TotalCount / pageSize)
                    }
                };
            }
            catch (Exception ex)
            {
                return new WebResponseContent
                {
                    Status = false,
                    Message = $"查询失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 根据销售单号查询销售明细列表
        /// </summary>
        public async Task<WebResponseContent> GetSalesOrderDetailsByCodeAsync(string shopOrderCode)
        {
            try
            {
                var result = await repository.GetSalesOrderDetailsByCodeAsync(shopOrderCode);

                return new WebResponseContent
                {
                    Status = true,
                    Message = "查询成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new WebResponseContent
                {
                    Status = false,
                    Message = $"查询销售明细失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 保存销售退货订单（包括主表和明细表）- 使用框架标准方法
        /// </summary>
        public async Task<WebResponseContent> SaveSalesReturnOrderAsync(SalesReturnOrderSaveRequest request)
        {
            return repository.DbContextBeginTransaction(() =>
            {
                try
                {
                    // 数据验证
                    if (request.MainData == null)
                    {
                        return new WebResponseContent
                        {
                            Status = false,
                            Message = "退货单主表数据不能为空"
                        };
                    }

                    if (request.DetailData == null || request.DetailData.Count == 0)
                    {
                        return new WebResponseContent
                        {
                            Status = false,
                            Message = "退货单明细数据不能为空"
                        };
                    }

                    // 验证退货数量
                    foreach (var detail in request.DetailData)
                    {
                        if (detail.returnQuantity <= 0)
                        {
                            return new WebResponseContent
                            {
                                Status = false,
                                Message = $"货品【{detail.goodsName}】的退货数量必须大于0"
                            };
                        }
                    }

                    // 获取当前用户信息
                    var currentUser = UserContext.Current.UserInfo;

                    // 生成退货单号（如果为空）
                    string orderCode = request.MainData.orderCode;
                    if (string.IsNullOrEmpty(orderCode))
                    {
                        orderCode = repository.GenerateReturnOrderCodeAsync().Result;
                    }

                    // 使用 Dictionary 保存主表（key 使用小驼峰，和实体类属性名一致）
                    var saveModel = new SaveModel
                    {
                        MainData = new Dictionary<string, object>
                        {
                            ["orderCode"] = orderCode,
                            ["salesOrderItemCode"] = request.MainData.salesOrderItemCode,
                            ["returnDate"] = request.MainData.returnDate,
                            ["supplierId"] = request.MainData.supplierId,
                            ["contact"] = request.MainData.contact,
                            ["contactPhone"] = request.MainData.contactPhone,
                            ["deptId"] = request.MainData.deptId,
                            ["userId"] = request.MainData.userId,
                            ["returnReason"] = request.MainData.returnReason,
                            ["remark"] = request.MainData.remark,
                            ["status"] = request.MainData.status ?? 1,  // 默认状态为草稿
                            ["auditor"] = request.MainData.auditor,
                            ["auditTime"] = request.MainData.auditTime,
                            ["customerName"] = request.MainData.customerName,
                            ["isDel"] = (sbyte)0,  // 逻辑删除标识，0表示未删除
                            ["createTime"] = DateTime.Now  // 创建时间
                        }
                    };

                    // 调用基类的 Add 方法保存主表
                    var mainResult = base.Add(saveModel);
                    if (!mainResult.Status)
                    {
                        return mainResult;
                    }

                    // 从saveModel.MainData中获取生成的主表ID
                    // 框架在保存后会自动将ID写回到MainData字典中
                    if (!saveModel.MainData.ContainsKey("Id"))
                    {
                        return new WebResponseContent
                        {
                            Status = false,
                            Message = "保存成功但无法获取主表ID"
                        };
                    }
                    
                    long returnOrderId = Convert.ToInt64(saveModel.MainData["Id"]);

                    // 保存明细表
                    if (request.DetailData != null && request.DetailData.Count > 0)
                    {
                        var returnOrderItemService = AutofacContainerModule.GetService<ISalesReturnOrderItemModelService>();
                        
                        foreach (var detail in request.DetailData)
                        {
                            // 计算退货金额
                            decimal returnAmount = 0;
                            if (detail.purchasePrice.HasValue && detail.returnQuantity.HasValue)
                            {
                                returnAmount = detail.purchasePrice.Value * detail.returnQuantity.Value;
                            }
                            
                            // 设置外键 - 使用主表的ID（key 使用小驼峰，和实体类属性名一致）
                            var detailSaveModel = new SaveModel
                            {
                                MainData = new Dictionary<string, object>
                                {
                                    ["returnOrderId"] = returnOrderId,  // 使用保存主表返回的ID
                                    ["purchaseOrderItemCode"] = detail.purchaseOrderItemCode,
                                    ["goodsId"] = detail.goodsId,
                                    ["goodsCode"] = detail.goodsCode,
                                    ["goodsName"] = detail.goodsName,
                                    ["specModel"] = detail.specModel,
                                    ["unitId"] = detail.unitId,
                                    ["unitName"] = detail.unitName,
                                    ["returnQuantity"] = detail.returnQuantity,
                                    ["purchasePrice"] = detail.purchasePrice,
                                    ["returnAmount"] = returnAmount,
                                    ["remarks"] = detail.remarks,
                                    ["stockOutItemId"] = detail.stockOutItemId,
                                    ["isDel"] = (sbyte)0,  // 逻辑删除标识
                                    ["createTime"] = DateTime.Now  // 创建时间
                                }
                            };
                            
                            var itemResult = returnOrderItemService.Add(detailSaveModel);
                            if (!itemResult.Status)
                            {
                                return new WebResponseContent { Status = false, Message = $"保存明细失败：{itemResult.Message}" };
                            }
                        }
                    }

                    return new WebResponseContent 
                    { 
                        Status = true, 
                        Message = "保存成功",
                        Data = new
                        {
                            OrderId = returnOrderId,
                            OrderCode = orderCode
                        }
                    };
                }
                catch (Exception ex)
                {
                    return new WebResponseContent
                    {
                        Status = false,
                        Message = $"保存失败：{ex.Message}"
                    };
                }
            });
        }
    }
}
